const util = require("../../utils/util")
const app = getApp()
Page({
  data: {
    TS: "发送点什么吧~",
    text: "", 
    myNickName: "", 
    scrollTop: 0,
    chatlist: { record: [] },
    recordID: "",
    watch: null
  },
  // 获取聊天记录
  getliaotian() {
    let that = this
    wx.cloud.database().collection('xinxi').doc(that.data.recordID).get({
      success(res) {
        console.log("聊天记录：", res.data)
        that.setData({
          chatlist: res.data
        }, () => {
          that.scrollToBottom();
        })
      },
      fail(err) {
        console.error("获取聊天记录失败:", err)
        wx.showToast({
          title: '获取记录失败',
          icon: 'none'
        })
      }
    })
  },
  // 开启实时监听
  startRealtimeListener() {
    const that = this;
    const db = wx.cloud.database();
    // 监听指定文档的变化
    this.data.watch = db.collection('xinxi').doc(this.data.recordID).watch({
      onChange: (snapshot) => {  
        console.log('收到文档更新', snapshot);
        if (snapshot.docs && snapshot.docs.length > 0) {
          this.setData({ 
            chatlist: snapshot.docs[0]
          }, () => {
            this.scrollToBottom(); 
          });
        }
      },
      onError: (err) => {
        console.error('监听失败', err);
      }
    });
  },
  // 停止实时监听
  stopRealtimeListener() {
    if (this.data.watch) {
      this.data.watch.close();
      this.setData({
        watch: null
      });
    }
  },
  scrollToBottom() {
    setTimeout(() => {
      this.setData({
        scrollTop: 999999 // 使用一个足够大的值
      });
    }, 100);
  },
  // 实时更新输入框内容
  onInput(e) {
    this.setData({
      text: e.detail.value
    })
  },
  // 发送消息 
  formSubmit(e) {
    console.log("表单提交触发", e.detail)
    const inputText = e.detail.value.text.trim();
    if (!inputText) {
      wx.showToast({
        title: '写点东西再发给TA吧~',
        icon: "none"
      })
      return
    }
    let that = this;
    const recordID = that.data.recordID;
    if (!recordID) {
      wx.showToast({
        title: '聊天ID不存在',
        icon: 'none'
      })
      return
    }
    
    const usernfo = app.globalData.userinfo?.[0] || {}; 
    if (!usernfo.nickName) {
      wx.showToast({
        title: '用户信息获取失败',
        icon: 'none'
      })
      return
    }
    const newMsg = {
      nickName: usernfo.nickName,
      Img: usernfo.faceImg || "/images/default-avatar.png",
      text: inputText,
      time: util.formatTime(new Date())
    };
    
    console.log("准备发送消息:", newMsg)
    const currentRecords = [...(that.data.chatlist.record || [])];
    currentRecords.push(newMsg);
    // 立即更新本地数据
    that.setData({
      'chatlist.record': currentRecords,
      text: "" 
    }, () => {
      that.scrollToBottom();
      // 然后更新据库
      wx.cloud.database().collection('xinxi').doc(recordID).update({
        data: { 
          record: currentRecords 
        },
        success(updateRes) {
          console.log("数据库更新成功", updateRes);
        },
        fail(err) {
          console.error("数据库更新失败", err);
          // 如果数据库更新失败，回退本地数据
          const originalRecords = currentRecords.slice(0, -1);
          that.setData({
            'chatlist.record': originalRecords
          });
          wx.showToast({ 
            title: '发送失败，请重试', 
            icon: 'none' 
          });
        }
      })
    })
  },
  onLoad(options) {
    console.log("接收的文档ID：", options.id);
    if (!options.id) {
      wx.showToast({ 
        title: '聊天参数错误', 
        icon: 'none' 
      });
      return;
    }
    this.setData({
      recordID: options.id,
      myNickName: app.globalData.userinfo?.[0]?.nickName || "我"
    });
    // 先获取一次数据
    this.getliaotian();
    // 然后开启实时监听
    this.startRealtimeListener();
  },
  onShow() {
    this.scrollToBottom();
    // 确保监听器在页面显示时是开启的
    if (!this.data.watch) {
      this.startRealtimeListener();
    }
  },
  onReady() {
    this.scrollToBottom();
  },
  onUnload() {
    // 页面卸载时停止监听
    this.stopRealtimeListener();
  },
  onHide() {
    // 页面隐藏时停止监听以节省资源
    this.stopRealtimeListener();
  }
})